
package com.zhu.salesmanagement;

import java.util.ArrayList;

import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.GoodsType;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.ProductInfoListView;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 经销商拜访界面
 */

public class DealerTaskListActivity extends Activity implements View.OnClickListener {

    private final static int INVALID_VALUE = -100;
    private final static String TAG = "zhu";
    private final static String SPLIT_ROW = ";";
    private final static String SPLIT_RANK = "&";
    private final static String DEFAULT = "default";
    private long mDBId = INVALID_VALUE;
    private final static int P_LIST_QUERY_TOKEN = 998;
    private final static int CP_LIST_QUERY_TOKEN = 999;
    private final static int CPNAME_LIST_QUERY_TOKEN = 997;
    private final static int GOODS_LIST_QUERY_TOKEN = 1000;
    private final static int GOODS_LIST_DELETE_TOKEN = 2000;

    public final static int DEALER_TYPE_ID = -1;

    private VisitTaskInfo mVisitTaskInfo = null;
    private TextView mNameTextView = null;
    //private TextView mRemindTextView = null;
    private LinearLayout mBodyView = null;
    private Spinner mSpinner = null;
    private boolean isFirst = true;
    private ArrayList<ProductInfo> lists = new ArrayList<ProductInfo>();
    private ArrayList<GoodsType> mGoodsTypeList = new ArrayList<GoodsType>();
    private int mCurrentTypeIndex = 0;
    private int mLastTypeIndex = 0;
    private View mRemindView = null;
    private FrameLayout mContentView = null;

    private String mGoodsId = "0";
    private GoodsListQueryHandler mGoodsListQueryHandler = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        Parcelable parcelable = getIntent().getParcelableExtra("info");
        mVisitTaskInfo = (VisitTaskInfo) parcelable;
        mGoodsId = mVisitTaskInfo.id;

        mGoodsListQueryHandler = new GoodsListQueryHandler(getContentResolver());

        setContentView(R.layout.dealerproductinfo_view);

        setupViews();
        initData();
    }

    /**
     * 初始化界面
     */
    private void setupViews() {
        mNameTextView = (TextView) findViewById(R.id.dealerlist_title);
        //mRemindTextView = (TextView) findViewById(R.id.dealerlist_remindname);
        mBodyView = (LinearLayout) findViewById(R.id.dealerlist_bodyView);
        mSpinner = (Spinner) findViewById(R.id.dealerlist_productSpinner);
        findViewById(R.id.dealerlist_back).setOnClickListener(this);
        findViewById(R.id.dealerlist_save2).setOnClickListener(this);
        findViewById(R.id.dealerlist_delete).setOnClickListener(this);
        mContentView = (FrameLayout) findViewById(R.id.derlerlist_content);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mNameTextView.setText(mVisitTaskInfo.mName/* + getResources().getString(R.string.dealer)*/);
        popRemindDialog(getRemindText(mGoodsId));
        //mRemindTextView.setText(getRemindText(mGoodsId));
        //initSpinner();
        //initListData();
        //updateBodyView();
        //startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(0).typeId);
        startCPsListAsyncQuery(mGoodsId);
    }

    /**
     * 获取货架信息数据
     * @param goodsId 门店ID
     */
    private void startCPsListAsyncQuery(String goodsId){
        try {
            mGoodsListQueryHandler.startQuery(CP_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductShelfsColumns.CONTENT_URI,
                    null, SalesSettings.ProductShelfsColumns.CUSTOMER_ID + "=\"" + goodsId +"\"", null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取大类产品列表
     * @param cpid 产品大类ID
     */
    private void startProductListAsyncQuery(String cpid){
        try {
            mGoodsListQueryHandler.startQuery(P_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductsColumns.CONTENT_URI,
                    null, SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID + " = \"" + cpid +"\"", null, "sort ASC");
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取大类名字数据
     * @param where 需要查询的大类
     */
    private void startCPNameListAsyncQuery(String where){
        try {
            mGoodsListQueryHandler.startQuery(CPNAME_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductCategoryColumns.CONTENT_URI,
                    null, where, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化大类选择栏
     */
    private void initSpinner() {
        intiGoodsTypeList();
        String[] name = new String[mGoodsTypeList.size()];
        for (int i = 0; i < name.length; i++) {
            name[i] = mGoodsTypeList.get(i).typeName;
        }
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, name);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                TextView tv = (TextView)arg1;
                tv.setTextColor(getResources().getColor(R.color.white));
                // TODO Auto-generated method stub
                mLastTypeIndex = mCurrentTypeIndex;
                mCurrentTypeIndex = arg2;
                if (!isFirst) {
                    saveCurrentGoodsInfo(mLastTypeIndex);
                    reset();
                } else {
                    isFirst = false;
                    mLastTypeIndex = mCurrentTypeIndex;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void intiGoodsTypeList() {
//        if (mGoodsTypeList != null) {
//            mGoodsTypeList.clear();
//        }
//        GoodsType goodsType1 = new GoodsType();
//        goodsType1.typeId = "XC";
//        goodsType1.typeName = "油类";
//
//        GoodsType goodsType2 = new GoodsType();
//        goodsType2.typeId = "CP";
//        goodsType2.typeName = "蔬菜类";
//        mGoodsTypeList.add(goodsType1);
//        mGoodsTypeList.add(goodsType2);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Actions.setAutoTime(this);
    }

    /**
     * button按键事件处理
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.dealerlist_back:
                    finish();
                    break;
                case R.id.dealerlist_delete:
                    popDeleteDialog();
                    break;
                case R.id.dealerlist_save2:
                    saveData();
                    break;
                case R.id.checkpop_close:
                    removeRemind();
                    break;
            }
        }
    };

    /**
     * 更新界面
     */
    private void updateBodyView() {
        if (mBodyView != null) {
            mBodyView.removeAllViews();
        }
        for (int i = 0; i < lists.size(); i++) {
            ProductInfo info = lists.get(i);
            View v = getView(info, i);
            mBodyView.addView(v);
        }
    }

    /**
     * 获取产品列表项view
     * @param info 产品信息
     */
    private View getView(ProductInfo info, int index) {
    	View view = LayoutInflater.from(this).inflate(R.layout.dealerproductinfolist_item, null);
        view.setTag(info);
        TextView title = (TextView) view.findViewById(R.id.dealeritem_title);
        title.setText(info.mName);
        EditText atext = (EditText) view.findViewById(R.id.dealeritem_text);
        atext.setText(info.mStock);
        return view;
    }

    private void updateViews(View view, int index, ProductInfo info, boolean isSetListener) {
        TextView textView1 = (TextView) view.findViewById(R.id.text1);
        EditText textView2 = (EditText) view.findViewById(R.id.text2);
        EditText textView3 = (EditText) view.findViewById(R.id.text3);
        EditText textView4 = (EditText) view.findViewById(R.id.text4);
        EditText textView5 = (EditText) view.findViewById(R.id.text5);

        textView1.setText(info.mName);
        textView2.setText(info.mFloor);
        textView3.setText(info.mSide);
        textView4.setText(info.mStock);
        textView5.setText(info.mPrice);

    }

    /**
     * 获取填写数据
     */
    private String getGoods() {
    	String content = "";
        ProductInfo temInfo = null;
        View view = null;
        for (int i = 0; i < mBodyView.getChildCount(); i++) {
            view = mBodyView.getChildAt(i);
            temInfo = (ProductInfo) view.getTag();
            if (temInfo.id == INVALID_VALUE) {
                continue;
            }
            updateProductInfoFormView(temInfo, view);
            if (temInfo.mStock == null || temInfo.mStock.trim().length() < 1) {
                temInfo.mStock = DEFAULT;
            }
            String row = temInfo.id + SPLIT_RANK + temInfo.mStock;
            content += (row + SPLIT_ROW);
        }
        return content;
    }

    /**
     * 更新界面显示数据
     * @param info 产品数据
     * @param view 界面
     */
    private void updateProductInfoFormView(ProductInfo info, View view) {
    	EditText textView4 = (EditText) view.findViewById(R.id.dealeritem_text);
        info.mStock = textView4.getText().toString().trim();
    }

    /**
     * 保存大类产品信息数据
     * @param index 当前选择大类索引
     */
    private void saveCurrentGoodsInfo(int index) {
        ContentValues values = new ContentValues();
        ContentResolver cr = this.getContentResolver();
        values.put(SalesSettings.GoodsInfoColumns.STOREID, mGoodsId);
        values.put(SalesSettings.GoodsInfoColumns.TYPEID, mGoodsTypeList.get(index).typeId);
        values.put(SalesSettings.GoodsInfoColumns.GOODS, getGoods());
        values.put(SalesSettings.GoodsInfoColumns.CREATE_TIME, System.currentTimeMillis());
        if (mDBId == INVALID_VALUE) {
            values.put(SalesSettings.GoodsInfoColumns.DTASKACTUALID, mVisitTaskInfo.mDatingTaskActualID);
            cr.insert(SalesSettings.GoodsInfoColumns.CONTENT_URI, values);
        } else {
            values.put(SalesSettings.GoodsInfoColumns._ID, mDBId);
            cr.update(SalesSettings.GoodsInfoColumns.getContentUri(mDBId, false), values, null,
                    null);
        }
    }

    /**
     * 保存当前大类产品数据
     */
    public void saveData() {
        try{
        	saveCurrentGoodsInfo(mCurrentTypeIndex);
            Actions.toastShort(this, this.getString(R.string.save_success));
            finish();
        }catch(Exception e){
            Actions.toastShort(this, this.getString(R.string.save_failed));
        }
    }

    private final class GoodsListQueryHandler extends AsyncQueryHandler {
        public GoodsListQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
            	case CP_LIST_QUERY_TOKEN:  //货架信息
            		intiGoodsTypeList(cursor);
            		break;
            	case CPNAME_LIST_QUERY_TOKEN: //大类名字
            		intiGoodsTypeNameList(cursor);
                break;
            	case P_LIST_QUERY_TOKEN: //产品列表
            		initProductListData(cursor);
                break;
                case GOODS_LIST_QUERY_TOKEN: //产品数据
                    updateListData(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case GOODS_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    /**
     * 更新产品数据
     * @param cursor 数据库内容
     */
    private void updateListData(Cursor cursor) {
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns._ID);
            final int goodsIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.GOODS);

            while (cursor.moveToNext()) {
                mDBId = cursor.getLong(idIndex);

                String goods = cursor.getString(goodsIndex);
                parseGoods(goods);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateListData error");
        } finally {
            cursor.close();
        }

        updateBodyView();
    }

    /**
     * 解析产品数据
     * @param goods 产品数据
     */
    private void parseGoods(String goods) {
        if (Actions.DEBUG) {
            Log.e("zhu", "goods=" + goods);
        }
        if(goods == null || goods.trim().length() == 0){
            if (Actions.DEBUG) {
                Log.e("zhu", "not have product");
            }
            return;
        }
        String[] rowGoods = goods.split(SPLIT_ROW);
        for (int i = 0; i < rowGoods.length; i++) {
            if (Actions.DEBUG) {
                Log.e("zhu", "xx=" + rowGoods[i]);
            }
            String[] rankGoods = rowGoods[i].split(SPLIT_RANK);
            ProductInfo temInfo = getProductInfo(Integer.parseInt(rankGoods[0]));
            if (rankGoods[1].equals(DEFAULT)) {
                rankGoods[1] = "";
            }
            temInfo.mStock = rankGoods[1];
        }
    }

    /**
     * 更具id获取产品信息
     * @param id
     */
    private ProductInfo getProductInfo(int id) {
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).id == id) {
                return lists.get(i);
            }
        }
        return null;
    }

    /**
     * 查询产品CRC数据
     * @param storeid 门店id
     * @param typeid  大类id
     */
    private void startGoodsListAsyncQuery(String storeid, String typeid) {
        try {
            mGoodsListQueryHandler.startQuery(GOODS_LIST_QUERY_TOKEN, null,
                    SalesSettings.GoodsInfoColumns.CONTENT_URI,
                    null, "storeid=? and typeid=?", new String[] {
                            storeid, typeid
                    }, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重置数据
     */
    private void reset() {
        mDBId = INVALID_VALUE;
        startProductListAsyncQuery(mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        //startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(mCurrentTypeIndex).typeId);
    }

    /**
     * 歇业门店提示
     */
    private void popDeleteDialog() {
        Actions.alertShowDetails(this, this.getString(R.string.stopbusinessclew),
                this.getString(R.string.stopbusinesscontent),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                    	boolean success = Util.saveStoresClose(DealerTaskListActivity.this, mVisitTaskInfo.mDbId);
                    	if(success){
                    		DealerTaskListActivity.this.setResult(RESULT_OK);
                    		DealerTaskListActivity.this.finish();
                    	}
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    /**
     * 更新大类货架信息
     * @param cursor 数据库数据
     */
    private void intiGoodsTypeList(Cursor cursor) {
        if (mGoodsTypeList != null) {
            mGoodsTypeList.clear();
        }
        String where = "";
        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID);
            final int scountIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_COUNT);
            final int slayerIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_LAYER);
            final int sareaIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_AREA);

            while (cursor.moveToNext()) {
                GoodsType item = new GoodsType();
                item.typeId = cursor.getString(pcIdIndex);
                item.sArea = cursor.getString(sareaIndex);
                item.sLayer = cursor.getString(slayerIndex);
                item.sCount = cursor.getString(scountIndex);
                if(item.typeId.equals(ProductInfoListView.MAIN_PC)){
                    mGoodsTypeList.add(0, item);
                }else{
                    mGoodsTypeList.add(item);
                }
                if(where.length() == 0){
                    where = SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.typeId + "\"";
                }else{
                    where += " or " + SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.typeId + "\"";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "intiGoodsTypeList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }

        if(mGoodsTypeList.size() > 0){
            startCPNameListAsyncQuery(where);
            startProductListAsyncQuery(mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        }
    }

    /**
     * 更新大类名字
     * @param cursor 数据库数据
     */
    private void intiGoodsTypeNameList(Cursor cursor){
        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID);
            final int pcNameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_NAME);

            while (cursor.moveToNext()) {
                GoodsType item = getGoodsType(cursor.getString(pcIdIndex));
                item.typeName = cursor.getString(pcNameIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "intiGoodsTypeNameList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        initSpinner();
    }

    /**
     * 更新大类id获取大类信息
     * @param typeid 大类id
     */
    private GoodsType getGoodsType(String typeid){
        for(int i =0; i < mGoodsTypeList.size(); i++){
            GoodsType type = mGoodsTypeList.get(i);
            if(type.typeId.equals(typeid)){
                return type;
            }
        }
        return null;
    }

    /**
     * 更新产品列表数据
     * @param cursor 数据库数据
     */
    private void initProductListData(Cursor cursor) {
        lists.clear();

        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID);
            final int pidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_ID);
            final int pnameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_NAME);

            while (cursor.moveToNext()) {
                ProductInfo info = new ProductInfo();
                info.id = Integer.parseInt(cursor.getString(pidIndex));
                info.mName = cursor.getString(pnameIndex);
                lists.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "initProductListData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        if(lists.size() > 0){
            startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        }else{
            updateBodyView();
        }
    }

    /**
     * 获取提醒数据
     * @param cid 门店ID
     */
    private String getRemindText(String cid){
        String remindtext = null;
        Cursor cursor = null;
        try{
            String where = SalesSettings.RemindsColumns.CUSTOMERID + " = \'" + cid +"\'";
            cursor = getContentResolver().query(SalesSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, null, where, null, null);
            while (cursor.moveToNext()) {
                String text = cursor.getString(cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.TEXT));
                if(text != null && text.length() > 0){
                    remindtext = text;
                    break;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            remindtext = null;
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
//        if(remindtext == null){
//            remindtext = getString(R.string.noremind);
//        }
        return remindtext;
    }

    /**
     * 弹出提醒界面
     */
    private void popRemindDialog(String content){
        if (content == null || content.trim().length() == 0) {
            return;
        }
        if (mRemindView == null) {
            mRemindView = getLayoutInflater().inflate(
                    R.layout.layout_popdialog, null);
            mRemindView.setOnClickListener(this);
            ImageView close = (ImageView) mRemindView
                    .findViewById(R.id.checkpop_close);
            close.setOnClickListener(this);
        }
        TextView name = (TextView) mRemindView
                .findViewById(R.id.checkpop_title);
        name.setText(getString(R.string.remindtitle));
        TextView text = (TextView) mRemindView.findViewById(R.id.checkpop_Text);
        text.setText(content);
        mContentView.addView(mRemindView);
    }

    /**
     * 删除提示界面
     */
    private void removeRemind(){
        if (mRemindView != null && mContentView.indexOfChild(mRemindView) != -1) {
            mContentView.removeView(mRemindView);
        }
    }

    /**
     * 处理返回键
     */
    private boolean doBack(){
        if(mContentView.indexOfChild(mRemindView) != -1){
            mContentView.removeView(mRemindView);
            return true;
        }
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                finish();
            }
            return true;
        }
        return false;
    }
}
